/*
 * sun_Net_Bag
 * 背包界面
 * 
 */

class Scene_Bag extends Scene_Base {
    initialize() {
        this.creatTestItem();
        super.initialize();
        NetMap.needPlacePlayer = true;
    }

    create() {
        super.create();
        // this.createBackground();
        this.updateActor();
        this.createWindowLayer();
        this.createAllWindow();
        this.createButton();
    }

    updateActor() {
        this._actor = NetManager.netActor();
    }

    createAllWindow() {
        this.createEquipWindow();
        this.createNameWindow();
        this.createBagWindow();
        this.createItemInfoWindow();
    }

    createEquipWindow() {
        const rect = this.equipWindowRect();
        this._equipWindow = new Window_Equip(rect);
        this.addWindow(this._equipWindow);
    }

    equipWindowRect() {
        const wx = 0;
        const ww = Graphics.boxWidth;
        const wh = 500;
        const wy = Graphics.boxHeight / 2 - wh;
        return new Rectangle(wx, wy, ww, wh);
    }

    createNameWindow() {
        const rect = this.nameWindowRect();
        this._nameWindow = new Window_ItemName(rect);
        this.addWindow(this._nameWindow);
    }

    nameWindowRect() {
        const wx = 0;
        const ww = Graphics.boxWidth;
        const wh = 60;
        const wy = Graphics.boxHeight / 2;
        return new Rectangle(wx, wy, ww, wh);
    }

    createBagWindow() {
        const rect = this.bagWindowRect();
        this._bagWindow = new Window_Bag(rect);
        this._bagWindow.setHandler("ok", this.onItemOk.bind(this));
        this.addWindow(this._bagWindow);
        this._bagWindow.setNameWindow(this._nameWindow);
    }

    bagWindowRect() {
        const wx = 0;
        const ww = Graphics.boxWidth;
        const wh = 440;
        const wy = Graphics.boxHeight / 2 + 60;
        return new Rectangle(wx, wy, ww, wh);
    }

    createItemInfoWindow() {
        const rect = this.infoWindowRect();
        this._infoWindow = new Window_ItemInfo(rect);
        this.addWindow(this._infoWindow);
        this._infoWindow.hide();
    }

    infoWindowRect() {
        const ww = 360;
        const wx = (Graphics.boxWidth - ww) / 2;
        const wh = 500;
        const wy = (Graphics.boxHeight - wh) / 2;
        return new Rectangle(wx, wy, ww, wh);
    }

    createButton() {
        const x = Graphics.boxWidth - 121;
        const y = 25;
        const button = new Sprite_Button("cancel");
        button.setClickHandler(this.popScene.bind(this));
        this._backButton = button;
        this.addChild(button);
        button.move(x, y);
    }

    onItemOk() {
        // if (this._infoWindow.visible) return;
        const item = this._bagWindow.itemAt(this._bagWindow.index());
        this._infoWindow.setItem(item);
        this._infoWindow.refresh();
        this._infoWindow.show();
    }

    creatTestItem() {
        const type = "weapon";
        const id = 3;
        let paramSeed;
        let appraisalSeed;
        NetManager.item = [];
        for (let i = 0; i < 10; i++) {
            paramSeed = Math.floor(Math.random() * 1000000);
            appraisalSeed = null;//Math.floor(Math.random() * 1000000);
            const data = { type, id, paramSeed, appraisalSeed }
            const item = new Net_Item(data);
            NetManager.item.push(item);
        }
    }
}

class Window_Bag extends Window_Selectable {
    initialize(rect) {
        super.initialize(rect);
        // this.setBackgroundType(2);
        this._data = [];
        this.activate();
        this.refresh();
    }

    colSpacing() {
        return 2;
    }

    rowSpacing() {
        return 2;
    }

    maxCols() {
        return 8;
    }

    maxItems() {
        return 30;
    }

    itemWidth() {
        return 85;
    }

    itemHeight() {
        return 85;
    }

    item() {
        return this.itemAt(this.index());
    }

    itemAt(index) {
        return this._data && index >= 0 ? this._data[index] : null;
    }

    makeItemList() {
        this._data = $gameParty.allItems();
    }

    drawItem(index) {
        const item = this.itemAt(index);
        if (item) {
            const rect = this.itemRect(index);
            const iconIndex = item.object().iconIndex;
            this.drawItemIcon(iconIndex, rect);
        }
    }

    drawItemIcon(iconIndex, rect) {
        const bitmap = ImageManager.loadSystem("IconSet");
        const pw = ImageManager.iconWidth;
        const ph = ImageManager.iconHeight;
        const sx = (iconIndex % 16) * pw;
        const sy = Math.floor(iconIndex / 16) * ph;
        const x = rect.x + 5;
        const y = rect.y + 5;
        const w = rect.width - 10;
        const h = rect.height - 10;
        this.contents.blt(bitmap, sx, sy, pw, ph, x, y, w, h);
    }

    refresh() {
        this.makeItemList();
        Window_Selectable.prototype.refresh.call(this);
    }

    setNameWindow(nameWindow) {
        this._nameWindow = nameWindow;
    }
    // drawBackgroundRect(rect) {
    //     const c1 = ColorManager.itemBackColor1();
    //     const c2 = ColorManager.itemBackColor2();
    //     const x = rect.x;
    //     const y = rect.y;
    //     const w = rect.width;
    //     const h = rect.height;
    //     this.contentsBack.gradientFillRect(x, y, w, h, c1, c2, true);
    //     this.contentsBack.strokeRect(x, y, w, h, c1);
    // }

    select(index) {
        super.select(index);
        const item = this.itemAt(index);
        if (item) {
            const name = item.object().name;
            this._nameWindow.setName(name);
        }

    }

    // redrawItem(index) {
    //     if (index >= 0) {
    //         this.clearItem(index);
    //         this.drawItemBackground(index);
    //         this.drawItem(index);
    //     }
    // }

}

class Window_ItemName extends Window_Base {
    initialize(rect) {
        super.initialize(rect);
        // this.setBackgroundType(2);
        this._data = "测试位置";
        this.contents.fontSize = 35;
        this.refresh();
    }

    setName(name) {
        this._data = name;
        this.refresh();
    }

    refresh() {
        this.contents.clear();
        this.drawText(this._data, 0, 0, 690, "center");
    }
}

class Window_Equip extends Window_Selectable {
    initialize(rect) {
        super.initialize(rect);
        // this.setBackgroundType(2);
        // this._data = "测试位置";
        // this.contents.fontSize = 35;
        this.refresh();
    }

    refresh() {
        // this.contents.clear();
        // this.drawText(this._data, 0, 0, 690, "center");
    }
}

class Window_ItemInfo extends Window_Base {
    initialize(rect) {
        super.initialize(rect);
        // this.setBackgroundType(2);
        this._data = null;
        this._y = 10;
        this._space = 35;
        this.contents.fontSize = 30;
        this.createButton();
        this.refresh();
    }

    refresh() {
        if (!this._data) return;
        this.contents.clear();
        this.resetTextColor();
        this._y = 10;
        this.drawBaseInfo();
        this.drawBaseParam();
        this.drawVaryingParam();
        this.drawAppraisalParam();
        this.refreshButton();
        // this.drawConditions();
    }

    drawBaseInfo() {
        const data = this._data.object();
        const x = 10;
        const w = this.width - 30;
        const goldIconIndex = 314;
        const type = this.getItemType();
        const baseInfo = `\\I[${data.iconIndex}]${data.name}x${this._data._num}     \\I[${goldIconIndex}]${data.price}`;
        const appraisal = this._data._appraisal.length > 0 ? "可鉴定" : "";
        const typeInfo = `${type[0]}     ${type[1]}     ${appraisal}`;
        this._y = 10;
        this.drawTextEx(baseInfo, x, this._y, w);
        this._y += this._space;
        this.drawTextEx(typeInfo, x, this._y, w);
        this._y += this._space;
    }

    drawBaseParam() {
        const data = this._data.object();
        const x = 10;
        const w = this.width - 30;
        const paramName = ["生命上限", "魔法上限", "物理攻击", "物理防御", "魔法攻击", "魔法防御", "出手速度", "幸运"];
        for (let i = 0; i < data.params.length; i++) {
            if (data.params[i] === 0) continue;
            const text = `${paramName[i]} + ${data.params[i]}`
            this.drawText(text, x, this._y, w);
            this._y += this._space;
        }
    }

    drawVaryingParam() {
        const data = this._data.object();
        if (!data.meta.Params) return;
        const x = 10;
        const w = this.width - 30;
        const paramName = { "mhp": "生命上限", "mmp": "魔法上限", "atk": "物理攻击", "def": "物理防御", "mat": "魔法攻击", "mdf": "魔法防御", "agi": "出手速度", "luk": "幸运" };
        const paramArr = data.meta.Params.split(",");
        const valueArr = data.meta.ParamsValue.split(",").map(Number);
        const rateArr = data.meta.ParamsRate.split(",").map(Number);
        this._seed = this._data._paramSeed;
        this.changeTextColor("#33FF00");
        for (let i = 0; i < paramArr.length; i++) {
            if (valueArr[i] === 0) continue;
            let name, text;
            const value = Math.round(valueArr[i] * (1 + this.random() * rateArr[i]));
            if (paramArr[i].charAt(paramArr[i].length - 1) === "%") {
                name = paramName[paramArr[i].substr(0, paramArr[i].length - 1)];
                text = `${name} + ${value}%`;
            } else {
                name = paramName[paramArr[i]];
                text = `${name} + ${value}`;
            }
            this.drawText(text, x, this._y, w);
            this._y += this._space;
        }
    }

    drawAppraisalParam() {
        const data = this._data.object();
        if (!data.meta.AppraisalNum) return;
        const paramArr = data.meta["A-Params"].split(",");
        const valueArr = data.meta["A-ParamsValue"].split(",").map(Number);
        const rateArr = data.meta["A-ParamsRate"].split(",").map(Number);
        const paramName = { "mhp": "生命上限", "mmp": "魔法上限", "atk": "物理攻击", "def": "物理防御", "mat": "魔法攻击", "mdf": "魔法防御", "agi": "出手速度", "luk": "幸运" };
        const x = 10;
        const w = this.width - 30;
        const appraisal = this._data._appraisal;
        const num = appraisal.length;
        this._seed = this._data._appraisalSeed;
        for (const param of appraisal) {
            let text;
            if (param === null) {
                text = "未鉴定属性";
                this.changeTextColor("#DCDCDC");
            } else {
                const index = Math.floor(paramArr.length * this.random());
                console.log(index);
                const param = paramArr[index];
                const value = Math.round(valueArr[index] * (1 + this.random() * rateArr[index]));
                let name;
                if (param.charAt(param.length - 1) === "%") {
                    name = paramName[param.substr(0, param.length - 1)];
                    text = `${name} + ${value}%`;
                } else {
                    name = paramName[paramArr[index]];
                    text = `${name} + ${value}`;
                }
                this.changeTextColor("#FF69B4");

            }
            this.drawText(text, x, this._y, w);
            this._y += this._space;
        }
    }

    random() {
        this._seed = (this._seed * 9301 + 49297) % 233280;
        return this._seed / 233280.0;
    }

    getItemType() {
        const item = this._data;
        const data = item.object();
        if (item._type === "weapon") {
            return ["武器", $dataSystem.weaponTypes[data.wtypeId]];
        } else if (item._type === "armor") {
            return ["防具", $dataSystem.weaponTypes[data.atypeId]];
        } else if (item._type === "item") {
            return ["道具", data.meta.type ? data.meta.type : "其他"];
        }
    }

    createButton() {
        this.createCloseButton();
        this.createAppraisalButton();
    }

    createCloseButton() {
        const x = this.width - 55;
        const y = 5;
        const bitmap = new Bitmap(50, 100);
        bitmap.fillRoundRect(0, 0, 50, 100 / 2, "#FF6600");
        bitmap.drawText("x", 0, 0, 50, 50, "center");
        const button = new Sprite_NetButton(x, y, bitmap, this.closeInfo.bind(this));
        this._closeButton = button;
        this.addChild(button);
    }

    createAppraisalButton() {
        const w = 120;
        const h = 50;
        const x = (this.width - w) / 2;
        const y = 0;
        const bitmap = new Bitmap(w, h * 2);
        bitmap.fillRoundRect(0, 0, w, h, "#DBDBDB");
        bitmap.fillRoundRect(0, h, w, h, "#BBFFFF");
        bitmap.drawText("属性鉴定", 0, 0, w, h, "center");
        const button = new Sprite_NetButton(x, y, bitmap, this.appraisal.bind(this));
        // button.hide();
        this._appraisalButton = button;
        this.addChild(button);
    }

    refreshButton() {
        if (this._appraisalButton) {
            const x = (this.width - this._appraisalButton.width) / 2;
            const y = this._y + 15;
            this._appraisalButton.move(x, y);
            this._appraisalButton.show();
        }
    }

    closeInfo() {
        this.hide();
        SceneManager._scene._bagWindow.activate();
    }

    appraisal() {
        //后面要改服务器生成！！
        const seed = Math.floor(Math.random() * 1000000);
        this._data.appraisal(seed);
        this.refresh();
    }

    setItem(item) {
        this._data = item;
    }
}